package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.enums.BaseStatus;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.SystemPost;
import com.atguigu.lease.web.admin.service.SystemPostService;
import com.atguigu.lease.web.admin.mapper.SystemPostMapper;
import org.springframework.stereotype.Service;

/**
 * @author gqs
 * @description 针对表【system_post(岗位信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class SystemPostServiceImpl extends ServiceImpl<SystemPostMapper, SystemPost>
    implements SystemPostService {

  @Override
  public boolean saveOrUpdateSystemPost(SystemPost systemPost) {
    // 岗位名称唯一校验
    Long id = systemPost.getId() == null ? -1L : systemPost.getId();
    try {
      SystemPost dbSystemPost =
          this.getOne(
              Wrappers.lambdaQuery(SystemPost.class)
                  .eq(SystemPost::getName, systemPost.getName())
                  .last("limit 1"));
      if (dbSystemPost != null && !dbSystemPost.getId().equals(id)) {
        throw new StgyException(ResultCodeEnum.SYSTEM_POST_EXISTS);
      }
    } catch (Exception e) {
      throw new StgyException(ResultCodeEnum.SYSTEM_POST_EXISTS);
    }
    return this.saveOrUpdate(systemPost);
  }

  @Override
  public boolean updateStatusByUserId(Long id, BaseStatus status) {
    boolean flag =
        this.update(
            Wrappers.lambdaUpdate(SystemPost.class)
                .eq(SystemPost::getId, id)
                .set(SystemPost::getStatus, status));
    return flag;
  }
}
